import re
from calendar import month_abbr

# 在字符串中搜索和匹配指定的文本模式
def demo_1():
    text = 'yeah, but no, but yeah, but no, but yeah'
    # replace方法替换目标字符串的所有匹配字符
    print(text.replace('yeah', 'yep'))
    print(text)
    text = text.replace('yeah', 'yep')
    print(text)

def demo_2():
    text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
    # sub函数第一个参数是被匹配的模式，第二个参数是替换模式，反斜杠数字比如 \3指向前面模式的捕获组号
    result = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)
    print(result)

    # 打算用相同的模式做多次替换，考虑先编译来提升性能
    datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
    result_1 = datepat.sub(r'\3-\1-\2', text)
    print(result_1)

def change_date(m):
    mon_name = month_abbr[int(m.group(1))]
    return '{}-{}-{}'.format(m.group(2), mon_name, m.group(3))

def demo_3():
    text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
    datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
    result = datepat.sub(change_date, text)
    print(result)
    newtext, n = datepat.subn(r'\3-\1-\2', text)
    print('{}, {}'.format(newtext, n))

if __name__ == '__main__':
    # demo_1()
    # demo_2()
    demo_3()